package com.iaz.tech.tools.common.utils;

import java.awt.Color;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.text.DecimalFormat;



import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.servlet.http.HttpServletResponse;
 
/**
 *  @Copyright 北京志行正科技有限公司
 *  @author 赵黎民
 *  @version 2021.08
 *  @description 公共类
 *
 */
public class UtilTools {
    private static String[] MONTH_CN = {"一","二","三","四","五","六","七","八","九","十","十一","十二"};

	private static String[] XUHAO = {"零","一","二","三","四","五","六","七","八","九"};
	private static String[] SHUWEI = {"十","百","千","万" };

	/**
	 * 去除字符串两边的空格
	 *
	 * @param param
	 * @return
	 */
	public static String Trim(String param) {
		return param == null ? "" : param.trim();
	}

	/**
	 * 判断是否是空字符串
	 *
	 * @param param
	 * @return
	 */
	public static Boolean IsNull(String param) {
		return param == null ? true : Trim(param).length() == 0;
	}

	/**
	 * 获得当前时间的时间戳，及从1970-1-1 到现在的时间的毫秒数
	 *
	 * @return
	 */
	public static long getCurrentTime() {
		long result = 0l;
		try {
			java.util.Date right = new java.util.Date();
			result = right.getTime();
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			return 0l;
		}
	}


	/**
	 * 将日期的Time 转换成必要的String ,
	 *
	 * @param _time
	 * @param fm
	 * @return
	 */
	public static String formatLongTime(long _time, String fm) {
		String result = "";

		try {
			String date_format = UtilTools.Trim(fm);

			Date dateTime = new Date(_time);
			SimpleDateFormat sdf = new SimpleDateFormat(date_format);
			result = sdf.format(dateTime);
		} catch (Exception e) {
			e.printStackTrace();
			result = "";
		}

		return result;
	}

	public static Boolean getBooleanValue( String _value ) {
		Boolean result = false;
		try {

			result = Boolean.parseBoolean( UtilTools.Trim(_value ));
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			return result;
		}
	}
	
	public static short getShortValue(String _string){
		short result = 0;
		try {
			if (UtilTools.IsNull(_string)) {
				return 0;
			}
			result = Short.parseShort(UtilTools.Trim(_string));
		} catch (NumberFormatException e) { 
			result = 0;
		}
		return result;
	}
	
	public static byte getByteValue(String _string){
		byte result = 0;
		try {
			if (UtilTools.IsNull(_string)) {
				return 0;
			}
			result = Byte.parseByte( UtilTools.Trim(_string));
		} catch (NumberFormatException e) { 
			result = 0;
		}
		return result;
	}

	/**
	 * 将字符串转换成整数（不抛异常）
	 * @param _string
	 * @return
	 */
	public static int getIntgerValue(String _string) {
		int result = -1;
		try {
			if (UtilTools.IsNull(_string)) {
				return 0;
			}
			result = Integer.parseInt(UtilTools.Trim(_string));
		} catch (NumberFormatException e) {
			e.printStackTrace();
			System.out.println("value:" + _string);
			result = -1;
		}
		return result;
	}


	public static int getIntgerValueEX202207(String _string) {
		int result = -1;
		try {
			if (UtilTools.IsNull(_string)) {
				return 0;
			}
			result = Integer.parseInt(UtilTools.Trim(_string));
		} catch (NumberFormatException e) {
			result = -1;
		}
		return result;
	}

	/**
	 * 将字符串转换成长整数（不抛异常）
	 * @param _string
	 * @return
	 */
	public static long getLongValue(String _string) {
		long result = -1;
		try {
			if (UtilTools.IsNull(_string)) {
				return 0;
			}
			result = Long.parseLong(UtilTools.Trim(_string));
		} catch (NumberFormatException e) {
			e.printStackTrace();
		}
		return result;

	}

	/**
	 * 将字符串转换成浮点数（不抛异常）
	 * @param _string
	 * @return
	 */
	public static float getFloatValue(String _string) {
		float result = Float.NaN;
		try {
			if (UtilTools.IsNull(_string)) {
				return result;
			}
			result = Float.parseFloat(UtilTools.Trim(_string));
		} catch (NumberFormatException e) { 
			result = Float.NaN;
		}
		return result;

	}

	/**
	 * 将字符串转换成双精度数（不抛异常）
	 * @param _string
	 * @return
	 */
	public static double getDoubleValue(String _string) {
		double result = Double.NaN;
		try {
			if (UtilTools.IsNull(_string)) {
				return result;
			}
			result = Double.parseDouble(UtilTools.Trim(_string));
		} catch (NumberFormatException e) {
			result = Double.NaN;
		}
		return result;

	}

	/**
	 * 将双精度的值，转换小数点2位的双精度的值
	 * @param _string
	 * @return
	 */
	public static double formatDouble(double _value) {
		double result = Double.NaN;
		if (Double.isNaN(_value))
			return result;
		DecimalFormat df = new DecimalFormat("0.00 ");

		result = getDoubleValue(df.format(_value));

		return result;
	}

	public static java.sql.Time toSqlTime(String string){
		java.sql.Time result = null;

		Date pDate = toDate(string);
		if( pDate == null ) return result;
		result = new java.sql.Time(pDate.getTime());

		return result;
	}

	public static java.sql.Timestamp toSqlTimestamp(String string){
		java.sql.Timestamp result = null;

		Date pDate = toDate(string);
		if( pDate == null ) return result;
		result = new java.sql.Timestamp(pDate.getTime());

		return result;
	}

//    public static boolean isLegealDateString(String value){
//    	if( UtilTools.IsNull(value)) return false;
//    	String tmp_value = UtilTools.Trim( value );
//    	String regex0 = "(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})/(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)/(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29)";
//    	String regex1 = "(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29)";
//    	String regex2 = "(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})年(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)月(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29)";
//
//    	String regex10 = "(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})/(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)/(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29)";
//    	String regex11 = "(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29)";
//    	String regex12 = "(([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})年(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)月(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29)";
//
//    	try{
//
//    		Pattern patter = Pattern.compile(regex0);
//
//    		return java.util.regex.Pattern.matches(regex, value);
//    	}catch(Exception e){
//    		return false;
//    	}
//    }
//
	/**
	 * 将字符串转换成日期格式
	 * @param string
	 * @return
	 */
	public static Date toDate(String string){
		Date result = null;
		if( UtilTools.IsNull( string )) return result;
		String t_string = UtilTools.Trim(string );
		
		try{
			result = toDate( t_string, "yyyy-MM-dd HH:mm:ss.SSS" );
			return result;
		}catch( Exception e ){

		}
		
		try{
			result = toDate( t_string, "yyyy-MM-dd HH:mm:ss" );
			return result;
		}catch( Exception e ){

		}
		
		try{
			result = toDate( t_string, "yyyy-MM-dd HH:mm" );
			return result;
		}catch( Exception e ){

		}
		
		try{
			result = toDate( t_string, "yyyy-MM-dd" );
			return result;
		}catch( Exception e ){

		}

		try{
			result = toDate( t_string, "yyyy/MM/dd HH:mm:ss.SSS" );
			return result;
		}catch( Exception e ){

		}

		try{
			result = toDate( t_string, "yyyy/MM/dd HH:mm:ss" );
			return result;
		}catch( Exception e ){

		}

		try{
			result = toDate( t_string, "yyyy/MM/dd HH:mm" );
			return result;
		}catch( Exception e ){

		}

		try{
			result = toDate( t_string, "yyyy/MM/dd" );
			return result;
		}catch( Exception e ){

		} 
		
		try{
			result = toDate( t_string, "MM/dd/yyyy HH:mm:ss.SSS" );
			return result;
		}catch( Exception e ){

		}
		
		try{
			result = toDate( t_string, "MM/dd/yyyy HH:mm:ss" );
			return result;
		}catch( Exception e ){

		}
		
		try{
			result = toDate( t_string, "MM/dd/yyyy HH:mm" );
			return result;
		}catch( Exception e ){

		}
		
		try{
			result = toDate( t_string, "MM/dd/yyyy" );
			return result;
		}catch( Exception e ){

		}
		 
		try{
			result = toDate( t_string, "HH:mm:ss.SSS" );
			return result;
		}catch( Exception e ){

		}
		
		try{
			result = toDate( t_string, "HH:mm:ss" );
			return result;
		}catch( Exception e ){

		}

		try{
			result = toDate( t_string, "HH:mm" );
			return result;
		}catch( Exception e ){

		} 
		return result;
	}

	private static Date toDate(String string, String fmt) throws Exception{
		Date result = null;

		if( UtilTools.IsNull( fmt)) throw new Exception("需要指定日期的格式！");

		String t_string = UtilTools.Trim(string );
		String t_fmt = UtilTools.Trim( fmt );

		SimpleDateFormat fm = new SimpleDateFormat(t_fmt);
		result = fm.parse( t_string );
		return result;
	}

	public static String fromDate(Date pdate,String fmt) {
		String result = "";
		try{
			if( UtilTools.IsNull( fmt)) throw new Exception("需要指定日期的格式！");
			String t_fmt = UtilTools.Trim( fmt );
			SimpleDateFormat fm = new SimpleDateFormat(t_fmt);
			result = fm.format(pdate);
		}catch(Exception e){
			e.printStackTrace();
			result = "";
		}
		return result;
	}

	   
	/**
	 * 替换所有的字符串
	 * @param source
	 * @param indexstring
	 * @param newString
	 * @return
	 */
	public static String replaceAll(String source, String indexstring, String newString){
		String result = source;

		String line = source;
		int index = line.indexOf(indexstring);
		if( index < 0 ){
			result = source;
			return result;
		}
		result = "";
		while( index>= 0 ){
			if( index > 0 ){
				result += line.substring(0, index);
			}
			result += newString;
			line = line.substring((index + indexstring.length()));
			index = line.indexOf(indexstring);
		}

		result += line;

		return result;
	}

	/**
	 * @apiNote 用于将Path 和file 关联成一个完整的路径，并检查path 是否是"\"或者"/”结尾，将重复"\"或者"/"自动合并成一个。
	 * @author 	Zhao limin
	 * @Version 2021
	 */
	public static String conactPathAndFile( String path, String file) throws Exception{
		String result = "";

		String tmpFile = UtilTools.Trim( path );
		StringBuffer sBuf =new StringBuffer();
		sBuf.append( tmpFile );
		if( ( tmpFile.lastIndexOf( "/") != (tmpFile.length() - 1 )  ) &&
				( tmpFile.lastIndexOf( "\\") != (tmpFile.length() - 1 ) ) ){
			sBuf.append("/");
		}

		sBuf.append(UtilTools.Trim(file )  );
		result = sBuf.toString();
		return result;
	}

	/**
	 * @apiNote 日期增加，并不抛异常。
	 * @author 	Zhao limin
	 * @Version 2021
	 */
	public static Date addDate(Date oldDate, int field, int amount ){
		Date result = null;
		try{
			Calendar calendar = Calendar.getInstance();
			calendar.setTime( oldDate );

			calendar.add( field, amount);
			result = calendar.getTime();
		}catch(Exception e){
			e.printStackTrace();
			result = null;
		}
		return result;
	}

	public static int getDatePart(Date oldDate, int field  ){
		int result = 0;
		try{
			Calendar calendar = Calendar.getInstance();
			calendar.setTime( oldDate );
			result = calendar.get( field );
		}catch(Exception e){
			e.printStackTrace();
			result = 0;
		}
		return result;
	}

	public static String getMonthCNOfDate(Date date){
		String result = "";
		int mon_index = getDatePart(date, Calendar.MONTH );

		if(mon_index < 0 ) return result;
		if( mon_index >= MONTH_CN.length  ) return result;

		result =  MONTH_CN[mon_index];

		return result;
	}

	public static String getFirstDayOfMonth( Date date){
		String result = "";
		try{
			String mon_string = fromDate( date, "yyyy-MM" );
			result = mon_string + "-01";
		}catch(Exception e){
			e.printStackTrace();
			result = "";
		}
		return result;
	}

	public static String generateObjectID(){
		String result = "";

		StringBuffer sBuf = new StringBuffer();

		sBuf.append(  UUID.randomUUID().toString().replaceAll("-",""));
		sBuf.append( "000000");
		result = sBuf.toString();
		return result;
	}

	public static String changeAlabo2CN(int num){
		String result = "";

		StringBuffer sBuf = new StringBuffer();
		int cusor_num = num;

		List<Integer> stack = new ArrayList<Integer>();
		while ( cusor_num > 0 ){
			int yushu = cusor_num % 10;
			cusor_num = cusor_num/ 10;
			if( stack.isEmpty() ){
				stack.add(yushu );
			} else{
				stack.add( 0, yushu);
			}
		}

		/* 亿为基础  最多支持到亿*/
		int end_index = stack.size() - 1;
		int i = 0;
		int ii = 0;
		boolean isZero = false;
		for( int index = end_index; index>=0; index--){


			if( i == SHUWEI.length  ){
				ii++;
				i = 0;
			}

			if( stack.get(index ) > 0 ){
				if( ii == 1  && i == 0 ){
					sBuf.insert(0, "万" );
				}

				if( ii == 2  && i == 0 ){
					sBuf.insert(0, "亿" );
				}
				if( i > 0 ){
					sBuf.insert(0, SHUWEI[ i ] );
				}
				sBuf.insert(0, XUHAO[ stack.get(index )] );
				isZero = false;
			}else if(!isZero ){
				sBuf.insert(0, "零" );
				isZero = true;
			}

			i++;

		}

		result = sBuf.toString();
		return result;
	}

	public static boolean existsStringInArray(List<String> stringlist, String value){
		boolean result = false;
		if( stringlist == null ) return result;
		if( stringlist.size() == 0 ) return result;
		if(UtilTools.IsNull( value )) return result;

		String tmp_value = UtilTools.Trim( value );

		for( String _str : stringlist ){
			if(UtilTools.IsNull( _str )) continue;

			String step_str = UtilTools.Trim( _str  );
			if(step_str.equalsIgnoreCase( tmp_value )){
				result = true;
				break;
			}
		}

		return result;
	}

	public static int getWeek( Date date ){
		int result = -1;

		if( date == null ) return result;

		Calendar calendar = Calendar.getInstance();
		calendar.setTime( date );

		result = calendar.get(Calendar.DAY_OF_WEEK);
		return result;
	}

	public static List<Date> getWeekDateForVeryDay(int month ) {
		List<Date> result = new ArrayList<Date>();

		try{
			Calendar calendar = Calendar.getInstance();

			calendar.set( Calendar.MONTH, month - 1);
			/**
			 * 获得当月的第一天
			 */
			Date fristDay = DateTimeUtils.getFirstDayOfMonth(calendar.getTime() );
			/**
			 * 获得当前时间最后一个天
			 */
			Date endDay = DateTimeUtils.getLastDayofMonth(calendar.getTime());

			int week = getWeek(fristDay);
			/*
			 *星期日:Calendar.SUNDAY=1
			 *星期一:Calendar.MONDAY=2
			 *星期二:Calendar.TUESDAY=3
			 *星期三:Calendar.WEDNESDAY=4
			 *星期四:Calendar.THURSDAY=5
			 *星期五:Calendar.FRIDAY=6
			 *星期六:Calendar.SATURDAY=7
			 */
			/* 往前 */
			while( week != Calendar.MONDAY ){
				fristDay = UtilTools.addDate( fristDay, Calendar.DAY_OF_YEAR, -1);
				week = getWeek(fristDay);
			}

			/* 计算 */
			int week_last = getWeek(endDay);
			while( week_last != Calendar.SUNDAY ){
				endDay = UtilTools.addDate( endDay, Calendar.DAY_OF_YEAR, 1);
				week_last = getWeek(endDay);
			}

			Date step_date = fristDay;

			while( step_date.getTime() <= endDay.getTime()){
				result.add( DateTimeUtils.getFristHourOfDay(step_date ) );
				step_date = UtilTools.addDate(step_date, Calendar.DAY_OF_YEAR, 1);
			}

		}catch(Exception e){

		}

		return result;
	}


	public static OutputStream getOutputStream(String fileName, HttpServletResponse response) throws Exception {
		try {
//            fileName = URLEncoder.encode(fileName, "UTF-8");
//            fileName = URLEncoder.encode(fileName, "UTF-8");
			response.setHeader("Access-Control-Allow-Origin", "*");
			response.setContentType("application/vnd.ms-excel");
			//response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

			response.setCharacterEncoding("utf8");
//            response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes(),"GBK") + ".xlsx");
			response.setHeader("Content-disposition", "attachment;filename*=utf-8'zh_cn'" + URLEncoder.encode(fileName, "UTF-8")+".xlsx");
			response.setHeader("Pragma", "public");
			response.setHeader("Cache-Control", "no-store");
			response.addHeader("Cache-Control", "max-age=0");
			return response.getOutputStream();
		} catch (IOException e) {
			throw new Exception("导出excel表格失败!", e);
		}
	}

	/*
     * Extension MIME Type
.doc      application/msword
.dot      application/msword

.docx     application/vnd.openxmlformats-officedocument.wordprocessingml.document
.dotx     application/vnd.openxmlformats-officedocument.wordprocessingml.template
.docm     application/vnd.ms-word.document.macroEnabled.12
.dotm     application/vnd.ms-word.template.macroEnabled.12

.xls      application/vnd.ms-excel
.xlt      application/vnd.ms-excel
.xla      application/vnd.ms-excel

.xlsx     application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.xltx     application/vnd.openxmlformats-officedocument.spreadsheetml.template
.xlsm     application/vnd.ms-excel.sheet.macroEnabled.12
.xltm     application/vnd.ms-excel.template.macroEnabled.12
.xlam     application/vnd.ms-excel.addin.macroEnabled.12
.xlsb     application/vnd.ms-excel.sheet.binary.macroEnabled.12

.ppt      application/vnd.ms-powerpoint
.pot      application/vnd.ms-powerpoint
.pps      application/vnd.ms-powerpoint
.ppa      application/vnd.ms-powerpoint

.pptx     application/vnd.openxmlformats-officedocument.presentationml.presentation
.potx     application/vnd.openxmlformats-officedocument.presentationml.template
.ppsx     application/vnd.openxmlformats-officedocument.presentationml.slideshow
.ppam     application/vnd.ms-powerpoint.addin.macroEnabled.12
.pptm     application/vnd.ms-powerpoint.presentation.macroEnabled.12
.potm     application/vnd.ms-powerpoint.template.macroEnabled.12
.ppsm     application/vnd.ms-powerpoint.slideshow.macroEnabled.12

.mdb      application/vnd.ms-access

     * */
	public static OutputStream getDocxOutputStream(String fileName, HttpServletResponse response) throws Exception {
		try {
//            fileName = URLEncoder.encode(fileName, "UTF-8");
//            fileName = URLEncoder.encode(fileName, "UTF-8");
			response.setHeader("Access-Control-Allow-Origin", "*");
			response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
			response.setCharacterEncoding("utf8");
//            response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes(),"GBK") + ".xlsx");
			response.setHeader("Content-disposition", "attachment;filename*=utf-8'zh_cn'" + URLEncoder.encode(fileName, "UTF-8")+".docx");
			response.setHeader("Pragma", "public");
			response.setHeader("Cache-Control", "no-store");
			response.addHeader("Cache-Control", "max-age=0");
			return response.getOutputStream();
		} catch (IOException e) {
			throw new Exception("导出excel表格失败!", e);
		}
	}

	public static OutputStream getDocxInlineOutputStream(String fileName, HttpServletResponse response) throws Exception {
		try {
//            fileName = URLEncoder.encode(fileName, "UTF-8");
//            fileName = URLEncoder.encode(fileName, "UTF-8");
			response.setHeader("Access-Control-Allow-Origin", "*");
			response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");
			response.setCharacterEncoding("utf8");
//            response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes(),"GBK") + ".xlsx");
			response.setHeader("Content-disposition", "inline;filename*=utf-8'zh_cn'" + URLEncoder.encode(fileName, "UTF-8")+".docx");
			response.setHeader("Pragma", "public");
			response.setHeader("Cache-Control", "no-store");
			response.addHeader("Cache-Control", "max-age=0");
			return response.getOutputStream();
		} catch (IOException e) {
			throw new Exception("导出excel表格失败!", e);
		}
	}


	public static OutputStream getJSONInlineOutputStream(String fileName, HttpServletResponse response) throws Exception {
		try {
//            fileName = URLEncoder.encode(fileName, "UTF-8");
//            fileName = URLEncoder.encode(fileName, "UTF-8");
			response.setHeader("Access-Control-Allow-Origin", "*");
			response.setContentType("application/json");
			response.setCharacterEncoding("utf8");
//            response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes(),"GBK") + ".xlsx");
			response.setHeader("Content-disposition", "inline;filename*=utf-8'zh_cn'" + URLEncoder.encode(fileName, "UTF-8")+".json");
			response.setHeader("Pragma", "public");
			response.setHeader("Cache-Control", "no-store");
			response.addHeader("Cache-Control", "max-age=0");
			return response.getOutputStream();
		} catch (IOException e) {
			throw new Exception("导出excel表格失败!", e);
		}
	}


	public static PrintWriter getJSONInlinePrintWriter(String fileName, HttpServletResponse response) throws Exception {
		try {
//            fileName = URLEncoder.encode(fileName, "UTF-8");
//            fileName = URLEncoder.encode(fileName, "UTF-8");
			response.setHeader("Access-Control-Allow-Origin", "*");
			response.setContentType("application/json");
			response.setCharacterEncoding("utf8");
//            response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes(),"GBK") + ".xlsx");
			response.setHeader("Content-disposition", "inline;filename*=utf-8'zh_cn'" + URLEncoder.encode(fileName, "UTF-8")+".json");
			response.setHeader("Pragma", "public");
			response.setHeader("Cache-Control", "no-store");
			response.addHeader("Cache-Control", "max-age=0");
			return response.getWriter();
		} catch (IOException e) {
			throw new Exception("导出excel表格失败!", e);
		}
	}

	public static PrintWriter getJSONDownloadPrintWriter(String fileName, HttpServletResponse response) throws Exception {
		try {
//            fileName = URLEncoder.encode(fileName, "UTF-8");
//            fileName = URLEncoder.encode(fileName, "UTF-8");
			response.setHeader("Access-Control-Allow-Origin", "*");
			response.setContentType("application/json");
			response.setCharacterEncoding("utf8");
//            response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes(),"GBK") + ".xlsx");
			response.setHeader("Content-disposition", "attachment;filename*=utf-8'zh_cn'" + URLEncoder.encode(fileName, "UTF-8")+".json");
			response.setHeader("Pragma", "public");
			response.setHeader("Cache-Control", "no-store");
			response.addHeader("Cache-Control", "max-age=0");
			return response.getWriter();
		} catch (IOException e) {
			throw new Exception("导出excel表格失败!", e);
		}
	}

	public static OutputStream getJSONDownLoadOutputStream(String fileName, HttpServletResponse response) throws Exception {
		try {
//            fileName = URLEncoder.encode(fileName, "UTF-8");
//            fileName = URLEncoder.encode(fileName, "UTF-8");
			response.setHeader("Access-Control-Allow-Origin", "*");
			response.setContentType("application/json");
			response.setCharacterEncoding("utf8");
//            response.setHeader("Content-Disposition", "attachment; filename=" + new String(fileName.getBytes(),"GBK") + ".xlsx");
			response.setHeader("Content-disposition", "attachment;filename*=utf-8'zh_cn'" + URLEncoder.encode(fileName, "UTF-8")+".json");
			response.setHeader("Pragma", "public");
			response.setHeader("Cache-Control", "no-store");
			response.addHeader("Cache-Control", "max-age=0");


			return response.getOutputStream();
		} catch (IOException e) {
			throw new Exception("导出excel表格失败!", e);
		}
	}

	public static Color fromStrToARGB(String str) {
		if( UtilTools.IsNull( str)) return null;
		String tmp_string = Trim(str);
		String str1 = Trim( tmp_string.substring(0, 2) );
		String str2 = Trim( tmp_string.substring(2, 4) );
		String str3 = Trim( tmp_string.substring(4, 6) );
		String str4 = Trim( tmp_string.substring(6, 8) );
		int alpha = Integer.parseInt(str1, 16);
		int red = Integer.parseInt(str2, 16);
		int green = Integer.parseInt(str3, 16);
		int blue = Integer.parseInt(str4, 16);
		Color color = new Color(red, green, blue, alpha);
		return color;
	}

	public static String getFileName(String fileName){
		String result = "";
		if( UtilTools.IsNull( fileName)) return result;

		int index_post = fileName.lastIndexOf(".docx");
		if( index_post >= 0 ){
			result = UtilTools.Trim( fileName.substring(0, index_post));
		}

		index_post = fileName.lastIndexOf(".DOCX");
		if( index_post >= 0 ){
			result = UtilTools.Trim( fileName.substring(0, index_post));
		}

		index_post = fileName.lastIndexOf(".doc");
		if( index_post >= 0 ){
			result = UtilTools.Trim( fileName.substring(0, index_post));
		}

		index_post = fileName.lastIndexOf(".DOC");
		if( index_post >= 0 ){
			result = UtilTools.Trim( fileName.substring(0, index_post));
		}

		index_post = result.lastIndexOf("/");
		if( index_post >= 0 ){
			result = UtilTools.Trim(result.substring(index_post + 1));
		}

		index_post = result.lastIndexOf("\\");
		if( index_post >= 0 ){
			result = UtilTools.Trim(result.substring(index_post + 1));
		}

		return result;
	}

	public static String[] splitStringAndTrims(String target, String[] splits ){
		String[] result = null;
		if( UtilTools.IsNull( target )) return result;
		if( splits == null ) return result;
		if( splits.length == 0 ) return result;

		List<String> words = new ArrayList<String>();

		String tmp_string = UtilTools.Trim( target );

		while(!UtilTools.IsNull( tmp_string )){
			int n_index = -1;

			String minsplit = "";
			for(String split : splits){
				int n_pos = tmp_string.indexOf( split );
				if( n_pos < 0 ) continue;

				if( n_index < 0 ){
					minsplit = split;
					n_index = n_pos;
				}else if( n_index > n_pos ){
					n_index = n_pos;
					minsplit = split;
				}
			}

			if( n_index < 0 ){
				/* 表示没有 */
				break;
			}

			words.add( UtilTools.Trim( tmp_string.substring( 0, n_index)) );
			tmp_string = tmp_string.substring(  n_index + minsplit.length() );
		}

		if( !UtilTools.IsNull( tmp_string )){
			words.add( UtilTools.Trim( tmp_string) );
		}

		if( words.size() > 0) {
			result = new String[words.size()];
			for( int i = 0; i < words.size(); i++ ){
				result[i] = words.get( i );
			}
		}

		words.clear();

		return result;
	}

	public static String[] splitStringAndTrim(String target, String spiltString) {
		String[] result = null;

		if( UtilTools.IsNull( target )){
			return result;
		}

		result =  target.split(spiltString);
		if( (result == null ) ||
				( result.length == 0 )){
			result = new String[1];
			result[0] = UtilTools.Trim( target );
		}

		for( int i = 0; i < result.length; i++ ){
			result[i] = UtilTools.Trim( result[i] );
		}

		return result;
	}

	/**
	 * 生成固定长度的字符串，不足的用0填充
	 * @param nvalue
	 * @param length
	 * @return
	 */
	public static String fixLengthStringForNumber(int nvalue, int length){
		String result = "";

		result = String.valueOf( nvalue);

		if( nvalue < 0 ){
			result = "0";
		}

		if( result.length() >= length){
			return result;
		}

		while(result.length() < length){
			result = "0" + result;
		}


		return result;
	}

	/**
	 * 生成OnlyOffice 的Key
	 * @return
	 */
	public static String generateOnlyOfficeNewKey() {
		String key = java.util.UUID.randomUUID().toString();
		key = key.substring( key.length() - 13);
		return key.replaceAll("-", "x") ;
	}

	/**
	 * 根据
	 * @param path
	 * @return
	 */
	public static String getFileIdFromPath(String path){
		String result = "";
		if( UtilTools.IsNull( path ) ) return result;

		String tmp_value = UtilTools.Trim( path );

		int str_length = tmp_value.length();

		/* 去掉.docx或者.doc */
		if( tmp_value.lastIndexOf( ".docx") == (str_length - ".docx".length() ) ){
			tmp_value = UtilTools.Trim( tmp_value.substring(0, (str_length - ".docx".length() )) );
		}
		else if( tmp_value.lastIndexOf( ".DOCX") == (str_length - ".DOCX".length() ) ){
			tmp_value = UtilTools.Trim( tmp_value.substring(0, (str_length - ".DOCX".length() ) ) );
		}
		else if( tmp_value.lastIndexOf( ".doc") == (str_length - ".doc".length() ) ){
			tmp_value = UtilTools.Trim( tmp_value.substring(0, (str_length - ".doc".length() ) ) );
		}
		else if( tmp_value.lastIndexOf( ".DOC") == (str_length - ".DOC".length() ) ){
			tmp_value = UtilTools.Trim( tmp_value.substring(0, (str_length - ".DOC".length() ) ) );
		}

		/* 判断 */
		int min_index = -1;

		int index = tmp_value.lastIndexOf( "\\");

		if( min_index == -1 ){
			min_index = index;
		}

		index = tmp_value.lastIndexOf( "/");
		if( min_index == -1 ){
			min_index = index;
		}else if( min_index < index ){
			min_index = index;
		}
		if( min_index > -1 ){
			result = tmp_value.substring( min_index + 1);
		}
		else {
			result = tmp_value;
		}

		return result;
	}
	/**
	 * 深度创建Path
	 * @param path
	 */
	public final static void createNewPaths(String path){
		try {
			if( UtilTools.IsNull( path )) {
				throw new Exception("路径名没有指定。");
			}
			String tmp_path = UtilTools.Trim(path);
			File file = new File(tmp_path);
			if( file.exists() ) {
				return ;
			}
			
			tmp_path = tmp_path.replaceAll("/", "\\");
			String[] string_split = new String[1];
			string_split[0] = "\\";			
			String[] paths = UtilTools.splitStringAndTrims(tmp_path, string_split);
			if (paths == null) {
				return;
			}
			if (paths.length == 0) {
				return;
			}
			String path_single_full = "";
			for (int i = 0; i < paths.length; i++) {
				String path_single = UtilTools.Trim( paths[i] );
				if (UtilTools.IsNull(path_single_full)) {
					path_single_full = path_single;
				}
				else {
					path_single_full = path_single_full + "\\" + path_single;
				}
				if( UtilTools.IsNull( path_single_full )) continue;
				File _file = new File( path_single_full );
				if( !_file.exists() ){
					_file.mkdir();
				}
			}
		} catch(Exception e){
			System.out.println("异常：" + e.getMessage());
		}
	}
}